package hrx.controller;

import hrx.entity.Admin;
import hrx.entity.Relation;
import hrx.entity.Task;
import hrx.entity.User;
import hrx.service.AdminService;
import hrx.service.FileUploadService;
import hrx.service.XsdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private XsdService xsdService;


    @Autowired
    private HttpSession session;

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 用户注册
     *
     * @param admin
     * @param model
     * @return
     */
    @RequestMapping("/register")
    public String register(Admin admin, Model model) {
        adminService.saveAdmin(admin);
        return "login";
    }

    /**
     * 登录校检
     *
     * @param admin
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(Admin admin, Model model) {
        Admin dbUser = adminService.findByName(admin);
        //判断是否相同
        if (dbUser != null && admin.getPassword().equals(dbUser.getPassword())) {
            //确实有这个用户
            session.setAttribute("admin", dbUser);
            //清空
            model.addAttribute("error", "");
            return "redirect:/index.html";
        } else {
            model.addAttribute("error", "没有这个admin");
            return "login";
        }
    }

    /**
     * 查询所有任务
     *
     * @return
     */
    @RequestMapping("/adminTaskPlatform")
    public String TaskList(Model model) {
        List<Task> allTasks = adminService.findAllTasks();
        model.addAttribute("tasks", allTasks);
        return "adminTaskPlatform";
    }

        /**
     * 查看任务详情
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/findByTask")
    public String findByTask(Integer id, Model model) {
        Task taskById = adminService.findTaskById(id);
        model.addAttribute("taskById", taskById);
        return "taskInfo";
    }
        /**
     * 查看接取人的详细信息
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/userInfo")
    public String userInfo(Integer id, Model model) {
        User byUserId = adminService.findByUser_id(id);
        model.addAttribute("user", byUserId);
        return "userInfo";
    }

    /**
     * 接受任务
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/acceptTask")
    public String acceptTask(Integer id, Model model) {
        Admin admin = (Admin) session.getAttribute("admin");
        Integer adminId = admin.getId();
        Relation relation = new Relation();
        relation.setTask_id(id);
        relation.setAdmin_id(adminId);

        //先查找任务信息
        Task task = adminService.findTaskById(id);
        Integer taskId = task.getId();
        Integer publisherId = task.getPublisher_id();

        //查询任务是否存在，不能重复接取
        Relation byUserIdAndTaskId = adminService.findByAdmin_idAndTask_id(relation);

        if (publisherId.equals(adminId)) {
            model.addAttribute("errorMessage", "不能接取自己发布的任务");
            return "error";
        } else if (byUserIdAndTaskId != null) {
            model.addAttribute("errorMessage", "已经接取过该任务，不能重复接取");
            return "error";
        } else {
            adminService.save(relation);
            session.setAttribute("relation", relation);
            model.addAttribute("successMessage", "成功");
            return "success";
        }
    }

    /**
     * 个人信息
     * @param model
     * @return
     */
    @RequestMapping("/adminIndex")
    public String adminIndex( Model model ) {
        Admin admin = (Admin) session.getAttribute("admin");
        model.addAttribute("admin", admin);
        return "adminIndex";
    }

    /**
     * 搜索任务
     * @param priceMin 最低价格
     * @param priceMax 最高价格
     * @param model
     * @return
     */
    @RequestMapping("/search")
    public String search(Task task, BigDecimal  priceMin, BigDecimal  priceMax, Model model) {

//        List<Task> taskList = adminService.findByTask(task,priceMin,priceMax);
        List<Task> taskList = adminService.TBFindAll(task,priceMin,priceMax);
        model.addAttribute("tasks", taskList);
        return "adminTaskPlatform";
    }

    /**
     * 查询用户信息
     * @param model
     * @return
     */
    @RequestMapping("/adminUser")
    public String adminUser(Model model) {
        List<User> userList = xsdService.findAll();
        model.addAttribute("userList", userList);
        return "adminUser";

    }

    /**
     * 查询用户余额
     * @param model
     * @return
     */
    @RequestMapping("/adminUserMoney")
    public String adminUserMoney(Model model) {
//        User user = xsdService.findByUser_id()
        return "adminUserMoney";
    }





//    /**
//     * 发布新任务
//     *
//     * @param task
//     * @return
//     */
//    @RequestMapping("/userTask")
//    public String userTask(Task task) {
//        User user = (User) session.getAttribute("loginUser");
//
//        //将用户信息存入新发布的任务中
//        task.setPublisher_id(user.getUser_id());
//        task.setPublisher_name((user.getUser_name()));
//
//        xsdService.saveTask(task);
//        return "redirect:/user/TaskList";
//    }
//
//
//    /**
//     * 删除任务
//     *
//     * @return
//     */
//    @RequestMapping("/deleteTask")
//    public String deleteTask(Integer id) {
//        xsdService.deleteTask(id);
//        return "redirect:/user/TaskList";
//    }
//
//
//
//    /**
//     * 资料修改页面
//     *
//     * @param id
//     * @param model
//     * @return
//     */
//    @RequestMapping("/userUpdateView")
//    public String userUpdateView(Integer id, Model model) {
//        User user = (User) session.getAttribute("loginUser");
//        model.addAttribute("loginUser", user);
//        return "userUpdate";
//    }
//
//    /**
//     * 资料修改
//     *
//     * @return
//     */
//    @RequestMapping("/userUpdate")
//    public String userUpdate(User user, Model model) {
//        xsdService.save(user);
//        return "redirect:/login.html";
//    }
//
//    /**
//     * 查看接受的任务id
//     * @param model
//     * @return
//     */
//    @RequestMapping("/userAtask")
//    public String userAtask( Model model) {
//        User user = (User) session.getAttribute("loginUser");
//        Integer user_id = user.getUser_id();
//
//        List<Relation> relationList = xsdService.findByUser_idRelation(user_id);
//        session.setAttribute("relationList", relationList);
//        return "redirect:/user/taskList";
//    }
//
//    /**
//     * 查询用户对应的任务
//     * @param model
//     * @return
//     */
//    @RequestMapping("/taskList")
//    public String taskList( Model model) {
//        List<Relation> relationList = (List<Relation>) session.getAttribute("relationList");
//
//        // 提取所有的 taskId
//        List<Integer> taskIds = relationList.stream()
//                .map(Relation::getTask_id)  // 假设 Relation 中有 getTaskId() 方法
//                .distinct()                // 去重
//                .collect(Collectors.toList());
//
//        List<Task> taskList = xsdService.findByIds(taskIds);
//        model.addAttribute("taskList", taskList);
//        return "userAtask";
//    }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//    /**
//     * 上传图片
//     *
//     * @return
//     */
//    @PostMapping("/uploadP")
//    public Map<String, Object> upload(@RequestParam("file") MultipartFile file,
//                                      HttpServletRequest request) {
//
//        System.out.println("=== 上传请求开始 ===");
//        System.out.println("文件名: " + file.getOriginalFilename());
//        System.out.println("文件大小: " + file.getSize());
//
//        // 验证文件
//        Map<String, Object> validation = fileUploadService.validateFile(file);
//        if (!(Boolean) validation.get("success")) {
//            Map<String, Object> errorResult = new HashMap<>();
//            errorResult.put("code", 1);
//            errorResult.put("msg", validation.get("message"));
//            return errorResult;
//        }
//
//        try {
//            //保存文件
//            String uploadPath = request.getServletContext().getRealPath("/uploads");
//            String fileName = fileUploadService.saveFile(file, uploadPath);
//
//            System.out.println("文件保存成功: " + fileName);
//
//            Map<String, Object> successResult = new HashMap<>();
//            successResult.put("code", 0);
//            successResult.put("msg", "上传成功");
//
//            Map<String, Object> data = new HashMap<>();
//            data.put("src", "/uploads/" + fileName);
//            data.put("title", file.getOriginalFilename());
//            successResult.put("data", data);
//
//            return successResult;
//
//        } catch (IOException e) {
//            Map<String, Object> errorResult = new HashMap<>();
//            errorResult.put("code", 1);
//            errorResult.put("msg", "文件保存失败");
//            return errorResult;
//        }
//    }
}


